package com.threeSales.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.threeSales.entity.Admin;
import com.threeSales.entity.User;

@Repository
public class UserDao {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	// 用户登录
	public User findUser(int name, String pwd) throws Exception {
		String sql = "select * from tb_user where name=? and passwords=?";
		User user = jdbcTemplate.queryForObject(sql, new Object[] {name, pwd }, new BeanPropertyRowMapper(User.class));
		return user;
	}

	// admin登陆
	public Admin findAdmin(int name, String pwd) throws Exception {
		String sql = "select * from tb_admin where name=? and passwords=?";
		Admin admin = jdbcTemplate.queryForObject(sql, new Object[] { name, pwd }, new BeanPropertyRowMapper(Admin.class));
		return admin;
	}
	
	//测试事物
	public void testadd() {
		jdbcTemplate.update("insert into tb_user(id,name,passwords,fid) values('xxxxx5',123,'44','234234')");
		System.out.println("测试事务是否运行");
	}

	//添加用户
	public int addUser(User user) {
		String sql = "insert into tb_user(id,name,passwords,fid) values(?,?,?,?)";
		Object[] params = { user.getId(), user.getName(), user.getPasswords(), user.getFid() };
		return jdbcTemplate.update(sql, params);
	}

	
	//根据id获取用户
	public  User findUser(String id){
		User user;
		try{
			String sql = "select * from tb_user where id=?";
			user = jdbcTemplate.queryForObject(sql, new Object[] {id},new BeanPropertyRowMapper(User.class));
		}catch(Exception e){
			user = null;
		}
		return user;
	}

}
